﻿using App_Start;
using BLL;
using Common.Class;
using Common.Model;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace RdpServer.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        /// <summary>
        /// 获取Token标识
        /// </summary>
        /// <returns>TokenID</returns>   
        public ServiceResultModel TokenIDGet()
        {
            ServiceResultModel _result = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                _result.Success = 1;
                string _guid = (Guid.NewGuid().ToString().Replace("-", ""));
                _result.Result = new
                {
                    TokenID = DateTime.Now.ToString("yyyyMMdd") + _guid.Substring(0, 10) + EncryptHelper.EncryptString_MD5(EncryptHelper.EncryptString_MD5(_guid.Substring(0, 10)).Substring(0, 5)).Substring(0, 5),

                };
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }


            return _result;


        }

        #region 客户端接口

        /// <summary>
        /// 客户端操作员是否已经登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel IsLogin()
        {
            ServiceResultModel _result = new ServiceResultModel()
            {
                Success = 0,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);

                if (!CacheHelper.Exists("AesKey_" + _tokenid))
                {
                    _result.Success = -999;
                    return _result;
                }

                if (CacheHelper.Exists("LoginUser_" + _tokenid))
                {
                    _result.Success = 1;
                }
                else
                {
                    _result.Success = 0;
                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }


            return _result;
        }

        /// <summary>
        /// 获取一次性随机Key
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel RandomKeyGet()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                string _guid = (Guid.NewGuid().ToString().Replace("-", ""));
                string _randomKey = DateTime.Now.ToString("yyyyMMddHHmmss")
                    + _guid.Substring(0, 10)
                    + EncryptHelper.EncryptString_MD5(EncryptHelper.EncryptString_MD5(_guid.Substring(0, 10)).Substring(0, 5)).Substring(0, 5);
                _result.Result = new
                {
                    RandomKey = _randomKey,

                };
                CacheHelper.CacheAdd("RandomKey_" + _tokenid, _randomKey, DateTime.Now.AddSeconds(30), -1);
                _result.Success = 1;


            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 保存客户端生成的AES加密Key信息
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ClientKey()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);

                string _aesKey = _jsonParam.GetVar("Key");

                _aesKey = EncryptHelper.DecryptString_RSA(_aesKey, StringHelper.Decompress(ConfigBLL.Config.RSAPrivateKey));

                if (!string.IsNullOrWhiteSpace(_aesKey))
                {
                    string _randomKey = Convert.ToString(CacheHelper.CacheGet("RandomKey_" + _tokenid));
                    if (!string.IsNullOrWhiteSpace(_randomKey))
                    {
                        if (_aesKey.Length > _randomKey.Length && _randomKey == _aesKey.Substring(0, _randomKey.Length))
                        {
                            CacheHelper.CacheRemove("RandomKey_" + _tokenid);
                            CacheHelper.CacheAdd("AesKey_" + _tokenid, _aesKey, null, 60 * 20);
                            _result.Success = 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;

        }

        /// <summary>
        /// 客户端登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel ClientLogin()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                string _aesKey = Convert.ToString(CacheHelper.CacheGet("AesKey_" + _tokenid));
                if (string.IsNullOrWhiteSpace(_aesKey))
                {
                    _result.Success = -999;
                    return _result;
                }
                JsonHelper _jsonParam = new JsonHelper(EncryptHelper.DecryptString_Aes(_paramStr, _aesKey));
                string _userID = _jsonParam.GetVar("UserID");
                string _password = _jsonParam.GetVar("Password");
                UserModel _user = UserBLL.UserGetFromUserID(_userID);
                if (_user != null)
                {
                    if (_user.Password == EncryptHelper.EncryptString_MD5(EncryptHelper.EncryptString_MD5(_password).Substring(0, 10)).Substring(0, 10))
                    {
                        CacheHelper.CacheAdd("LoginUser_" + _tokenid, _user, null, 60 * 20);
                        _result.Success = 1;

                        UserLogModel _userLog = new UserLogModel();
                        _userLog.ID = CommonHelper.GetNewID();
                        _userLog.UserID = _user.ID;
                        _userLog.LogKey = "UserLogin";
                        string _logValue = "用户ID:" + Convert.ToString(_user.ID);
                        _logValue += "|" + "用户名:" + _user.UserName;
                        _userLog.LogValue = _logValue;
                        UserBLL.UserLogAdd(_userLog);
                    }
                }

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;

        }

        /// <summary>
        /// 获取用户会话列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel UserSessionListGet()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                string _aesKey = Convert.ToString(CacheHelper.CacheGet("AesKey_" + _tokenid));
                if (string.IsNullOrWhiteSpace(_aesKey))
                {
                    _result.Success = -999;
                    return _result;
                }

                UserModel _user = CacheHelper.CacheGet("LoginUser_" + _tokenid) as UserModel;
                if (_user == null)
                {
                    //登录超期，重新登录
                    _result.Success = -998;
                    return _result;
                }

                List<SessionModel> _sessionList = new List<SessionModel>();

                if (_user.IsAdmin == "Y")
                {
                    _sessionList = SessionBLL.SessionListGet();
                }
                else
                {
                    _sessionList = UserBLL.UserSessionListGet(_user.ID.Value);
                }

                _result.Success = 1;
                _result.Result = EncryptHelper.EncryptString_Aes(JsonHelper.GetJsonStrFromObject(new { SessionList = _sessionList }), _aesKey);


            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;


        }

        /// <summary>
        /// 根据会话ID获取会话信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel UserSessionGetFromID()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                string _aesKey = Convert.ToString(CacheHelper.CacheGet("AesKey_" + _tokenid));
                if (string.IsNullOrWhiteSpace(_aesKey))
                {
                    _result.Success = -999;
                    return _result;
                }

                UserModel _user = CacheHelper.CacheGet("LoginUser_" + _tokenid) as UserModel;
                if (_user == null)
                {
                    //登录超期，重新登录
                    _result.Success = -998;
                    return _result;
                }

                JsonHelper _jsonParam = new JsonHelper(EncryptHelper.DecryptString_Aes(_paramStr, _aesKey));
                string _sessionID = _jsonParam.GetVar("SessionID");

                List<SessionModel> _sessionList = new List<SessionModel>();

                if (_user.IsAdmin == "Y")
                {
                    _sessionList = SessionBLL.SessionListGet();
                }
                else
                {
                    _sessionList = UserBLL.UserSessionListGet(_user.ID.Value);
                }

                SessionModel session = SessionBLL.SessionGetFromID(_sessionList, Convert.ToInt64(_sessionID)).session;


                //增加会话连接日志
                UserLogModel _userLog = new UserLogModel();
                _userLog.ID = CommonHelper.GetNewID();
                _userLog.UserID = _user.ID;
                _userLog.LogKey = "SessionConnect";
                string _logValue = "操作员:" + _user.UserName;
                _logValue += "|" + "会话ID:" + Convert.ToString(session.ID);
                if (session.SessionType == SessionType.SessionRdpClient)
                {
                    RdpSessionModel _rdpSession = JsonHelper.GetObjectFromJsonStr<RdpSessionModel>(JsonHelper.GetJsonStrFromObject(session.Data));
                    _logValue += "|" + " 连接地址:" + _rdpSession.Server;
                }
                _userLog.LogValue = _logValue;
                UserBLL.UserLogAdd(_userLog);

                if (session != null)
                {
                    _result.Success = 1;
                    _result.Result = EncryptHelper.EncryptString_Aes(JsonHelper.GetJsonStrFromObject(new { Session = session }), _aesKey);
                }
                else
                {
                    _result.ErrorMessage = "会话信息不存在";
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel ClientUserChangePassword()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                string _aesKey = Convert.ToString(CacheHelper.CacheGet("AesKey_" + _tokenid));
                if (string.IsNullOrWhiteSpace(_aesKey))
                {
                    _result.Success = -999;
                    return _result;
                }

                UserModel _user = CacheHelper.CacheGet("LoginUser_" + _tokenid) as UserModel;
                if (_user == null)
                {
                    //登录超期，重新登录
                    _result.Success = -998;
                    return _result;
                }

                JsonHelper _jsonParam = new JsonHelper(EncryptHelper.DecryptString_Aes(_paramStr, _aesKey));
                string _oldPassword = _jsonParam.GetVar("OldPassword");
                string _newPassword = _jsonParam.GetVar("NewPassword");

                if (_user != null)
                {
                    _user = UserBLL.UserGetFromID(_user.ID.Value);
                    _user.IsInitOK = true;
                    if (_user.Password == EncryptHelper.EncryptString_MD5(EncryptHelper.EncryptString_MD5(_oldPassword).Substring(0, 10)).Substring(0, 10))
                    {

                        _user.Password = EncryptHelper.EncryptString_MD5(EncryptHelper.EncryptString_MD5(_newPassword).Substring(0, 10)).Substring(0, 10);
                        UserBLL.UserUpdate(_user);
                        _result.Success = 1;

                    }
                }

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        #endregion

        #region 服务器网页端接口

        /// <summary>
        /// 是否需要密码登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ServiceResultModel NeedLoginPassword()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);

                if(SessionBLL.SessionList==null)
                {
                    SessionBLL.SessionListGet();
                }
                
                if (string.IsNullOrWhiteSpace(SessionBLL.LoginPassword))
                {
                    CacheHelper.CacheAdd("TokenID_" + _tokenid, _tokenid, null, 60 * 20);
                    _result.Success = 1;
                    _result.Result = new { NeedLoginPassword = 0, IsMastLocal = ConfigBLL.Config.IsMastLocal };
                    return _result;
                }


                if (!string.IsNullOrWhiteSpace(Convert.ToString(CacheHelper.CacheGet("TokenID_" + _tokenid))))
                {
                    _result.Success = 2;
                    return _result;
                }

                SessionBLL.SessionListGet();

                _result.Success = 1;
                _result.Result = new { NeedLoginPassword = 1, IsMastLocal = ConfigBLL.Config.IsMastLocal };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 修改是否必须使用127.0.0.1域名在服务器访问网站
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel ChangeIsMastLocal()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                //角色名
                string _isMastLocal = _jsonParam.GetVar("IsMastLocal");
                if (string.IsNullOrWhiteSpace(_isMastLocal))
                {
                    _result.ErrorMessage = "请选择选项";
                    return _result;
                }

                ConfigBLL.Config.IsMastLocal = _isMastLocal.ToLower() == "true" ? true : false;

                _result.Success = 1;
                _result.Result = new { IsMastLocal = ConfigBLL.Config.IsMastLocal };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 修改登录密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel ChangeLoginPassword()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                //原密码
                string _oldPassword = _jsonParam.GetVar("OldPassword");
                //新密码
                string _newPassword = _jsonParam.GetVar("NewPassword");

                if ((!string.IsNullOrWhiteSpace(SessionBLL.LoginPassword)) && EncryptHelper.DecryptString_Aes(SessionBLL.LoginPassword, "JlPwd") != _oldPassword.Trim())
                {
                    _result.ErrorMessage = "原密码错误";
                    return _result;
                }
                if (_newPassword.Trim() == "")
                {
                    SessionBLL.LoginPassword = "";
                }
                else
                {
                    SessionBLL.LoginPassword = EncryptHelper.EncryptString_Aes(_newPassword.Trim(), "JlPwd");
                }
                SessionBLL.SessionListSave(SessionBLL.SessionList);


                _result.Success = 1;
                _result.Result = "";

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 管理网站登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        public ServiceResultModel Login()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                string _tokenid = Convert.ToString(Request.Form["TokenID"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                //登录密码
                string _loginPassword = _jsonParam.GetVar("LoginPassword");

                SessionBLL.SessionListGet();

                if ((!string.IsNullOrWhiteSpace(SessionBLL.LoginPassword)) && _loginPassword.Trim() != EncryptHelper.DecryptString_Aes(SessionBLL.LoginPassword, "JlPwd"))
                {
                    _result.ErrorMessage = "密码错误";
                    return _result;
                }
                else
                {
                    _result.Success = 1;
                    CacheHelper.CacheAdd("TokenID_" + _tokenid, _tokenid, null, 60 * 20);
                }

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel RoleList()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                Dictionary<long, RoleModel> _roleList = RoleBLL.RoleListGet();

                _result.Success = 1;
                _result.Result = new { RoleList = _roleList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 新增角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel RoleAdd()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                //角色名
                string _roleName = _jsonParam.GetVar("RoleName");
                if (string.IsNullOrWhiteSpace(_roleName))
                {
                    _result.ErrorMessage = "角色名不可为空";
                    return _result;
                }

                RoleModel _role = new RoleModel();
                _role.ID = CommonHelper.GetNewID();
                _role.RoleName = _roleName;
                _role.DeleteFlag = "N";
                RoleBLL.RoleAdd(_role);

                Dictionary<long, RoleModel> _roleList = RoleBLL.RoleListGet();

                _result.Success = 1;
                _result.Result = new { RoleList = _roleList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel RoleUpdate()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                //角色名
                string _roleName = _jsonParam.GetVar("RoleName");
                if (string.IsNullOrWhiteSpace(_roleName))
                {
                    _result.ErrorMessage = "角色名不可为空";
                    return _result;
                }


                RoleModel _role = RoleBLL.RoleGetFromID(Convert.ToInt64(_id));
                if (_role == null)
                {
                    _result.ErrorMessage = "角色信息错误";
                    return _result;
                }

                _role.IsInitOK = true;
                _role.RoleName = _roleName;
                _role.DeleteFlag = "N";
                RoleBLL.RoleUpdate(_role);

                Dictionary<long, RoleModel> _roleList = RoleBLL.RoleListGet();

                _result.Success = 1;
                _result.Result = new { RoleList = _roleList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel RoleDelete()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                RoleModel _role = RoleBLL.RoleGetFromID(Convert.ToInt64(_id));
                if (_role == null)
                {
                    _result.ErrorMessage = "角色信息错误";
                    return _result;
                }

                _role.IsInitOK = true;
                _role.DeleteFlag = "Y";
                RoleBLL.RoleUpdate(_role);

                Dictionary<long, RoleModel> _roleList = RoleBLL.RoleListGet();

                _result.Success = 1;
                _result.Result = new { RoleList = _roleList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 获取角色关联的会话
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel RoleSessionListGet()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                RoleModel _role = RoleBLL.RoleGetFromID(Convert.ToInt64(_id));
                if (_role == null)
                {
                    _result.ErrorMessage = "角色信息错误";
                    return _result;
                }

                List<long> _sessionIDs = RoleBLL.RoleSessionListGet(_role.ID.Value);

                _result.Success = 1;
                _result.Result = new { SessionIDs = _sessionIDs };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 增加角色关联会话
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel RoleSessionListAdd()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _roleid = _jsonParam.GetVar("RoleID");
                string _sessionIDs = _jsonParam.GetVar("SessionIDs");
                RoleModel _role = RoleBLL.RoleGetFromID(Convert.ToInt64(_roleid));
                if (_role == null)
                {
                    _result.ErrorMessage = "角色信息错误";
                    return _result;
                }

                List<long> _ids = JsonHelper.GetObjectFromJsonStr<List<long>>(_sessionIDs);

                RoleBLL.RoleSessionListAdd(_role.ID.Value, _ids);

                _result.Success = 1;
                _result.Result = new { SessionIDs = _sessionIDs };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }



        /// <summary>
        /// 客户端操作员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserList()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                Dictionary<long, UserModel> _userList = UserBLL.UserListGet();

                _result.Success = 1;
                _result.Result = new { UserList = _userList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserAdd()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                //登录名
                string _userid = _jsonParam.GetVar("UserID");
                //用户名
                string _userName = _jsonParam.GetVar("UserName");
                //是否超级管理员
                string _isAdmin = _jsonParam.GetVar("IsAdmin");
                //登录密码
                string _password = _jsonParam.GetVar("Password");
                if (string.IsNullOrWhiteSpace(_userid))
                {
                    _result.ErrorMessage = "登录名不可为空";
                    return _result;
                }
                if (string.IsNullOrWhiteSpace(_userName))
                {
                    _result.ErrorMessage = "用户名不可为空";
                    return _result;
                }
                if (string.IsNullOrWhiteSpace(_password))
                {
                    _result.ErrorMessage = "密码不可为空";
                    return _result;
                }

                UserModel _model = new UserModel();
                _model.ID = CommonHelper.GetNewID();
                _model.UserID = _userid;
                _model.UserName = _userName;
                _model.IsAdmin = _isAdmin == "Y" ? "Y" : "N";
                _model.Password = EncryptHelper.EncryptString_MD5(_password.Substring(0, 10)).Substring(0, 10);
                _model.DeleteFlag = "N";
                UserBLL.UserAdd(_model);

                Dictionary<long, UserModel> _modelList = UserBLL.UserListGet();

                _result.Success = 1;
                _result.Result = new { UserList = _modelList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserUpdate()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                //登录名
                string _userid = _jsonParam.GetVar("UserID");
                //用户名
                string _userName = _jsonParam.GetVar("UserName");
                //是否超级管理员
                string _isAdmin = _jsonParam.GetVar("IsAdmin");
                if (string.IsNullOrWhiteSpace(_userid))
                {
                    _result.ErrorMessage = "登录名不可为空";
                    return _result;
                }
                if (string.IsNullOrWhiteSpace(_userName))
                {
                    _result.ErrorMessage = "操作员名不可为空";
                    return _result;
                }

                UserModel _model = UserBLL.UserGetFromID(Convert.ToInt64(_id));
                if (_model == null)
                {
                    _result.ErrorMessage = "操作员信息错误";
                    return _result;
                }

                _model.IsInitOK = true;
                _model.UserID = _userid;
                _model.UserName = _userName;
                _model.IsAdmin = _isAdmin == "Y" ? "Y" : "N";
                _model.DeleteFlag = "N";
                UserBLL.UserUpdate(_model);

                Dictionary<long, UserModel> _modelList = UserBLL.UserListGet();

                _result.Success = 1;
                _result.Result = new { UserList = _modelList.Values.ToList() };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserDelete()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                UserModel _model = UserBLL.UserGetFromID(Convert.ToInt64(_id));
                if (_model == null)
                {
                    _result.ErrorMessage = "操作员信息错误";
                    return _result;
                }
                _model.IsInitOK = true;
                _model.DeleteFlag = "Y";
                UserBLL.UserUpdate(_model);

                Dictionary<long, UserModel> _modelList = UserBLL.UserListGet();

                _result.Success = 1;
                _result.Result = new { UserList = _modelList.Values.ToList() };
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserChangePassword()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                string _password = _jsonParam.GetVar("Password");
                if (string.IsNullOrWhiteSpace(_password))
                {
                    _result.ErrorMessage = "登录密码不可为空";
                    return _result;
                }

                UserModel _model = UserBLL.UserGetFromID(Convert.ToInt64(_id));
                if (_model == null)
                {
                    _result.ErrorMessage = "操作员信息错误";
                    return _result;
                }

                _model.IsInitOK = true;
                _model.Password = EncryptHelper.EncryptString_MD5(_password.Substring(0, 10)).Substring(0, 10);
                UserBLL.UserUpdate(_model);


                _result.Success = 1;

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 获取操作员关联的角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserRoleListGet()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _id = _jsonParam.GetVar("ID");
                UserModel _user = UserBLL.UserGetFromID(Convert.ToInt64(_id));
                if (_user == null)
                {
                    _result.ErrorMessage = "操作员信息错误";
                    return _result;
                }

                List<long> _roleIDs = UserBLL.UserRoleListGet(_user.ID.Value);

                _result.Success = 1;
                _result.Result = new { RoleIDs = _roleIDs };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        /// <summary>
        /// 增加角色关联会话
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserRoleListAdd()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {

                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _userid = _jsonParam.GetVar("UserID");
                string _roleIDs = _jsonParam.GetVar("RoleIDs");
                UserModel _user = UserBLL.UserGetFromID(Convert.ToInt64(_userid));
                if (_user == null)
                {
                    _result.ErrorMessage = "操作员信息错误";
                    return _result;
                }

                List<long> _ids = JsonHelper.GetObjectFromJsonStr<List<long>>(_roleIDs);

                UserBLL.UserRoleListAdd(_user.ID.Value, _ids);

                _result.Success = 1;

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }


        /// <summary>
        /// 客户端操作员操作日志列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel UserLogList()
        {
            ServiceResultModel _result = new ServiceResultModel() { Success = 0 };

            try
            {
                string _paramStr = Convert.ToString(Request.Form["ParamStr"]);
                JsonHelper _jsonParam = new JsonHelper(_paramStr);
                string _beginTimes = _jsonParam.GetVar("BeginTime");
                string _endTimes = _jsonParam.GetVar("EndTime");
                DateTime _beginTime = DateTime.Parse(_beginTimes);
                DateTime _endTime = DateTime.Parse(_endTimes);

                List<UserLogModel> _userList = UserBLL.UserLogListGet(_beginTime, _endTime);

                _result.Success = 1;
                _result.Result = new { UserLogList = _userList };

            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "---" + MethodBase.GetCurrentMethod().Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
#endif
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _result;
        }

        #endregion


    }

}
